import ctypes
if ctypes.windll.kernel32.GetConsoleWindow() !=0:
    ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(),0)
    ctypes.windll.kernel32.CloseHandle(ctypes.windll.kernel32.GetConsoleWindow(),0)

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from smtplib import SMTP_SSL
from time import sleep
from PIL import Image
import datetime
import shutil
import signal
import os,sys
try:
    from mss import mss
except:
    os.system("pip install mss")
    from mss import mss

def signal_handler(signal, frame):
    global smtp
    smtp.quit()
    try:
        os.remove('3.monitor-1.png')
        os.remove('3.this.png')
        os.remove('3.this.last.png')
    except:
        pass
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

sleep(70)

fa = os.getcwd() + '//' + '3.monitor-1.png'
fb = os.getcwd() + '//' + '3.this.png'
fc = os.getcwd() + '//' + '3.this.last.png'

times_stuck = 0

d_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date())+'8:00', '%Y-%m-%d%H:%M')
d_time2 =  datetime.datetime.strptime(str(datetime.datetime.now().date())+'12:00', '%Y-%m-%d%H:%M')
d_time3 =  datetime.datetime.strptime(str(datetime.datetime.now().date())+'13:00', '%Y-%m-%d%H:%M')
d_time4 =  datetime.datetime.strptime(str(datetime.datetime.now().date())+'17:30', '%Y-%m-%d%H:%M')

while True:

    mss().shot(output=fa)

    Image.open(fa).crop((220,448,937,548)).save(fb,'PNG')
    
    if not os.path.exists(fc):
        shutil.copy(fb, fc)
        continue
    
    if os.path.getsize(fb) == os.path.getsize(fc):
        times_stuck += 1
    else:
        times_stuck = 0

    if times_stuck >=2:

        email_receiver='2907821379@qq.com'
        email_title='电脑界面卡顿了！'
        email_content='请速速解决！'

        smtp_serv = 'smtp.qq.com'
        smtp_port = 465
        smtp_addr = '2674075194@qq.com'
        smtp_name = '2674075194'
        smtp_pass = 'cutiqdkrautqebba'
        
        smtp = SMTP_SSL(smtp_serv, smtp_port)
        smtp.set_debuglevel(0)
        smtp.ehlo(smtp_serv)
        smtp.login(smtp_name,smtp_pass)
        msg = MIMEMultipart()
            #email_content, 'plain', 'utf-8')
        msg["Subject"]=email_title
        msg["From"]=smtp_addr
        msg["To"]=email_receiver
        
        file_attach=fa
        with open(file_attach, "rb") as f:
            part = MIMEApplication(f.read(), Name=os.path.basename(file_attach))
            msg.attach(part)

        n_time = datetime.datetime.now()
        if (n_time > d_time1 and n_time<d_time2) or (n_time > d_time3 and n_time<d_time4):
            smtp.sendmail(smtp_addr, email_receiver, msg.as_string())

        smtp.close()
        try:
            os.remove(fa)
            os.remove(fb)
            os.remove(fc)
        except:
            pass
        sys.exit(0)
 
    
    sleep(4)
    shutil.copy(fb, fc)


